package cn.edu.zjx.controller;

import com.management.entity.Role;
import com.management.service.RoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/role")
public class RoleController {

    private static final Logger logger = LoggerFactory.getLogger(RoleController.class);

    @Autowired
    private RoleService roleService;

    // 显示角色列表的页面
    @RequestMapping("/role")
    public String Listinfo() {
        return "role";
    }

    // 获取所有角色
    @GetMapping("/list")
    public String list(Model model) {
        try {
            model.addAttribute("roles", roleService.getAllRoles());
            return "role/list";
        } catch (Exception e) {
            logger.error("获取角色列表失败", e);
            model.addAttribute("error", "获取角色列表失败");
            return "error";
        }
    }

    // 显示添加角色页面
    @GetMapping("/add")
    public String add() {
        return "role/add";
    }

    // 处理添加角色的请求
    @PostMapping("/add")
    @ResponseBody
    public String add(Role role) {
        return roleService.addRole(role) ? "success" : "error";
    }

    // 显示编辑角色页面
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable Integer id, Model model) {
        try {
            model.addAttribute("role", roleService.getRoleById(id));
            return "role/edit";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "加载编辑页面失败");
            return "error";
        }
    }

    // 处理编辑角色的请求
    @PostMapping("/edit")
    @ResponseBody
    public String edit(Role role) {
        return roleService.updateRole(role) ? "success" : "error";
    }

    // 处理删除角色的请求
    @PostMapping("/delete/{id}")
    @ResponseBody
    public String delete(@PathVariable Integer id) {
        return roleService.deleteRole(id) ? "success" : "error";
    }

    // 搜索角色
    @GetMapping("/search")
    public String search(String keyword, Model model) {
        try {
            model.addAttribute("roles", roleService.searchRoles(keyword));
            return "role/list";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "搜索角色失败");
            return "error";
        }
    }
}
